<template>
  <div :class="'chart'+className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts' // echarts theme
import resize from './mixins/resize'
require('echarts/theme/macarons')

export default {
  mixins: [resize],
  props: {
    className: {
      type: String
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    barChartData: {
      type: Object
    }
  },
  data () {
    return {
      chart: null
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.initChart()
    })
    window.addEventListener('resize', () => {
      this.chart.resize()
    })
  },
  beforeDestroy () {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  watch: {
    barChartData: {
      deep: true,
      handler (val) {
        this.setOptions(val)
      }
    }
  },
  methods: {
    initChart () {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.barChartData)
    },
    setOptions ({ title, seriesData, xAxisNameData } = {}) {
      // {
      //     name: '未处理',
      //     type: 'bar',
      //     stack: 'vistors',
      //     barWidth: '60%',
      //     data: untreated,
      //     animationDuration: 2800,
      //     animationEasing: 'quadraticOut'
      //   }
      // var seriesData = []
      console.log(seriesData)
      var arr = []
      if (seriesData && seriesData.length > 0) {
        seriesData.map(item => {
          arr.push(
            {
              name: item.name,
              type: 'bar',
              stack: 'vistors',
              barMaxWidth: 30,
              barWidth: '50%',
              data: item.data,
              animationDuration: 2800,
              animationEasing: 'quadraticOut'
            }
          )
        })
      }
      this.chart.setOption({
        title: {
          text: title,
          textStyle: {
            color: '#409EFF'
          },
          padding: [0, 0, 10, 100]
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: 30,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          axisLabel: {
            rotate: 25
          },
          data: xAxisNameData,
          axisTick: {
            alignWithLabel: true
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          }
        }],
        series: arr
      })
    }
  }

}
</script>
